import json
import os
import re
import uuid

from django.contrib.auth import logout, login
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User
from iHome.settings.dev import logger, QINIU_DOMIN_PREFIX
from iHome.utils.image import storage
from iHome.utils.view import LoginRequiredJSONMixin


class UserHouseView(LoginRequiredJSONMixin,View):
    def get(self, request):
        """
        获取用户房屋列表
        1. 获取当前登录用户
        2. 查询房屋数据返回数据
        """
        user = request.user
        try:
            houses = user.house_set.all()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': "查询数据失败"})

        houses_dict = []
        for house in houses:
            houses_dict.append({
                "house_id": house.id,
                "title": house.title,
                "price": house.price,
                "area_name": house.area.name,
                "img_url": house.index_image_url,
                "room_count": house.room_count,
                "order_count": house.order_count,
                "address": house.address,
                "user_avatar": house.user.avatar_url,
                "ctime": house.create_time.strftime("%Y-%m-%d")
            })
        return JsonResponse({'errno': 0, 'errmsg': "OK", 'data': houses_dict})


class Session(View):
    '''用户状态查询'''

    def get(self, request):
        """
        检测用户是否登录，如果登录，则返回用户的名和用户id
        """
        user = request.user
        if user.is_authenticated:
            data = {'user_id': user.id, 'name': user.username}
            return JsonResponse({'errno': 0, 'errmsg': "OK", 'data': data})
        else:
            return JsonResponse({'errno': 4101, 'errmsg': '用户未登录'})


class Logout(LoginRequiredJSONMixin,View):


    '''用户退出'''

    def delete(self, request):
        """
        1. 清除session中的对应登录之后保存的信息
        """
        # 清楚session
        logout(request)
        return JsonResponse({'errno': 0, 'errmsg': "用户已退出"})


class Login(View):
    '''登录'''

    def post(self, request):
        """
        用户登录
        1. 获取参数并对参数进行校验
        2. 从数据库查询出指定的用户
        3. 校验密码
        4. 保存用户登录状态
        5. 返回结果
        """
        # 1. 获取参数和判断是否有值
        data_dict = json.loads(request.body.decode())

        mobile = data_dict.get("mobile")
        password = data_dict.get("password")

        if not all([mobile, password]):
            return JsonResponse({'errno': 4103, 'errmsg': "参数不全"})

        # 2. 从数据库查询出指定的用户
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': "用户不存在"})

        # 3. 校验密码
        if not user.check_password(password):
            return JsonResponse({'errno': 4106, 'errmsg': "密码错误"})

        # 4. 保存用户登录状态
        login(request, user)

        # 5. 返回结果
        return JsonResponse({'errno': 0, 'errmsg': "登录成功"})

class UserCenterView(LoginRequiredJSONMixin, View):
    '''用户中心'''
    def get(self,request):
        #个人信息界面的查询
        try:
            data={
                'name':request.user.username,
                'avatar_url':request.user.avatar_url,
                'mobile':request.user.mobile
            }
        except Exception as e:
            print('错误：',e)
            return JsonResponse({
                'errno':4001,'errmsg':'DBERR'
            })

        return JsonResponse({
            'errno':0,'errmsg':'OK',
            'data':data
        })

    def post(self,request):
        '''修改用户信息'''
        #接收参数解析
        json_dict =json.loads(request.body.decode())

        new_name =json_dict.get('name')

        #校验参数
        if new_name==None:
            return JsonResponse({
                'errno':'4103','errmsg':'参数不能为空'
            })
        #修改数据库姓名
        user = request.user
        try:
            user.username = new_name
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'errno':4004,'errmsg':'姓名修改失败'
            })
        return JsonResponse({
            'errno':0,'errmsg':'姓名更新成功'
        })


class UserImage(View):

    def post(self, request):

        user = request.user
        # 1:提取参数
        image_file = request.FILES.get('avatar',None)

        # 2:校验参数
        if image_file is None:
            return JsonResponse({
                "code": 400,
                "errmsg": "图片没有输入，不能上传"
            }, status=400)

        # 3:数据处理---读取数据(二进制)，上传到七牛云，将返回的地址，保存到数据库
        image_data = image_file.read()

        try:
            file_name = storage(image_data)

        except Exception as e:
            return JsonResponse({
                "code":400,
                "errmsg": "图片上传失败"
            })
        avatar_url = QINIU_DOMIN_PREFIX + file_name
        try:
            User.objects.filter(pk=user.id).update(avatar_url=avatar_url)

        except Exception as e:
            print(e)
            return JsonResponse({
                "code": 400,
                "errmsg": "图片保存失败"
            })

        #  avatar_url = "http://qglpphun0.hn-bkt.clouddn.com/" + file_name
        # 4:构建响应
        return JsonResponse({
            "errno": 0,
            "errmsg": "ok",
            "data": {"avatar_url": avatar_url},
        })

class shiMing(View):
    def get(self,request):
        '''查询用户实名信息'''
        user=None
        try:
            user =User.objects.filter(username=request.user).get()
            print(user)
        except Exception as e:
            print('错误：',e)

        #参数校验
        if user==None:
            return JsonResponse({
                'errno':4104,'errmsg':'USERERR'
            })
        real_name = user.real_name
        id_card = user.id_card
        if not all([real_name,id_card]):
            return JsonResponse({
                'errno':4002,'errmsg':'无用户实名信息'
            })
        data ={'real_name':real_name,'id_card':id_card}

        #返回数据
        return JsonResponse({
            'errno':0,'errmsg':'success',
            'data':data
        })

    def post(self,request):
        '''修改用户实名信息'''
        user =request.user
        json_dict = json.loads(request.body)
        real_name = json_dict.get("real_name")
        id_card=json_dict.get('id_card')

        # 参数校验
        if user == None:
            return JsonResponse({
                'errno': 4104, 'errmsg': '用户身份不存在或未激活'
            })
        if not all([real_name,id_card]):
            return JsonResponse({
                'errno':4004,'errmsg':'数据不能为空'
            })
        #修改数据库
        user.real_name =real_name
        user.id_card =id_card
        user.save()

        return JsonResponse({'errno':0,'errmsg':'ok'})


# 用户注册类视图
class RegisterView(View):
    # 请求方式 : post
    def post(self,request):
        # 1.接受参数
        json_dict = json.loads(request.body)

        # 2.解析参数
        # 手机号
        mobile = json_dict.get('mobile')
        # 短信验证码
        phonecode = json_dict.get('phonecode')
        # 第一次输入的密码
        password = json_dict.get('password')
        # 第二次输入的密码
        password2 = json_dict.get('password2')

        # 3.校验参数
        # --手机号 ----正则表达式
        if not re.match('^1[3-9]\d{9}$', mobile):
            return JsonResponse({"errno": 400, "errmsg": "手机号格式错误"})

        # --校验该手机是否已经注册
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            user = None  # 如果查询时出现错误，也需要给user初始化，如果不初始化，会报未定义的异常

        if user:
            return JsonResponse({'errno': 400, 'errmsg': "该手机已被注册"})

        # --短信验证码
        client = get_redis_connection('verify_code')  # 链接redis 2号库
        client_redis_phonecode = client.get(f'sms_{mobile}').decode()  # 获取数据库中的短信验证码(转换成字符串格式）
        if phonecode != client_redis_phonecode:  # 判断用户输入的验证码是否与数据库中的验证码一样
            return JsonResponse({"errno": 400, "errmsg": "短信验证码输入错误"})

        # --如果数据库中验证码不存在
        if not client_redis_phonecode:  # 验证码不在数据库中
            return JsonResponse({"errno": 400, "errmsg": "短信验证码已过期"})

        # --密码--最少6位,最多20位
        if not re.match('^[a-zA_Z0-9]{6,20}$', password):
            return JsonResponse({"errno": 400, "errmsg": "密码格式错误"})

        # --重复密码  --判断两次密码是否输入一致
        if password != password2:
            return JsonResponse({"errno": 400, "errmsg": "两次密码不一致"})

        # 4.处理业务逻辑

        try:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        except:
            return JsonResponse({"errno": 0, "errmsg": "注册失败!"})

        # 保持登录状态
        from django.contrib.auth import login
        login(request, user)

        # 5.返回响应对象
        response = JsonResponse({"errno": 400, "errmsg": "注册成功"})
        # 设置cookie,时间为24小时
        response.set_cookie('username', user.username, max_age=24*3600)
        return response
